package com.yc.leetcode;

public class Solution {
    public static void main(String[] args) {
        Solution s = new Solution();
        String a = "";
        System.out.println(s.decodeString(a));
    }

    int cur = 0;
    int n = 0;
    String ss = null;
    StringBuilder sb = new StringBuilder();


    public String decodeString(String s) {
        ss = s;
        n = s.length();
        return decode();
    }

    //解析字符串
    public String decode() {
        while (cur < n) {
            int num = getDigit();
            String str = getString();

            sb.setLength(0);
            for (int i=0; i<num; i++) {
                sb.append(str);
            }
        }

        return sb.toString();
    }

    //获得数字
    public int getDigit() {
        int res = 0;
        while(cur < n && Character.isDigit(ss.charAt(cur))) {
            res = res * 10 + (ss.charAt(cur) - '0');
        }
        return res;
    }

    //获得字符串(从[开始)
    public String getString() {
        sb.setLength(0);
        while(++cur < n) {//从[的下一个字符开始
            if (Character.isDigit(ss.charAt(cur))) {//又出现数字，继续递归 <-----
                sb.append(decode());
            } else if(ss.charAt(cur) == ']') {//结束:中间不会遇到并列的]，每一层都只负责自己]
                cur++;//每一段代码都要保证，出来的时候指针位于下一个要处理的字符
                break;
            } else {//字母
                sb.append(ss.charAt(cur)+"");
            }
        }
        return sb.toString();
    }
}
